package com.leyou.task;

import com.leyou.gateway.client.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author xiuer
 * @description 定时任务，定时获取token
 * @create 2019/7/11 9:29
 */
@Component
@Slf4j
public class PrivilegeTokenHolder {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthClient authClient;

    private String token;


    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * token 拉取失败的重试时间
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    /**
     * 定时拉取token
     *
     * @throws InterruptedException
     */
    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadingToken() throws InterruptedException {
        while (true) {
            try {
                token = authClient.authorize(jwtProperties.getApp().getId(), jwtProperties.getApp().getSecret());
                log.info("【网关微服务】拉取token成功 token为:{},", token);
                break;
            } catch (Exception e) {
                log.info("【网关微服务】拉取失败 原因;{},id {} secret {}", e.getMessage(),
                        jwtProperties.getApp().getId(), jwtProperties.getApp().getSecret(), e);
            }
            //休眠10s再次重试
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }
    }

    public String getToken() {
        return token;
    }
}
